#!/usr/bin/perl

use Math::BigInt;

($dir, $target, $num) = @ARGV;

&failed("can not chdir $dir $!") unless(chdir($dir));
&failed("$num <= 0") if($num <= 0);
$target =~ s|.*problems/2chTripSearchEx/||;
$target =~ tr/+/ /;
$target =~ s/%([0-9A-Fa-f][0-9A-Fa-f])/pack('H2', $1)/eg;

($target, $start, $end) = split(/\s+/, $target, 3);

$startBigInt = &str2int($start);
$endBigInt = &str2int($end);
$all = $endBigInt;
$all->bsub($startBigInt);
$diff = $all;
$diff->bdiv($num);

foreach $n ( 1 .. $num ){
	my($startCharBigInt) = $diff->as_int();
	$startCharBigInt->bmul($n-1);
	$startCharBigInt->badd($startBigInt);
	my($endCharBigInt) = $diff->as_int();
	$endCharBigInt->bmul($n);
	$endCharBigInt->badd($startBigInt);
	$endCharBigInt->bsub(1) if($n != $num);
	$startString = &int2str($startCharBigInt);
	$endString = &int2str($endCharBigInt);
	open(FILE, ">$n") || &failed("file $n can not created $!");
	print FILE "$target\n$startString\n$endString\n";
	close(FILE);
}
&success();

sub success {
	exit(0);
}
sub failed {
	#print(@_, "\n");
	exit(1);
}

sub str2int{
	my($str) = @_;
	@chars = unpack("C8", $str);
	my($startChar) = 33;
	my($endChar) = 126;
	my($char, $num);
	$num = Math::BigInt->new(0);
	foreach $char (@chars){
		$num *= ($endChar - $startChar);
		$num += $char - $startChar;
	}
	return $num;
}

sub int2str{
	my($bigInt) = @_;
	my(@chars);
	my($startChar) = 33;
	my($endChar) = 126;
	while($bigInt > 0){
		my($quo, $rem) = $bigInt->bdiv($endChar - $startChar);
		push(@chars, pack("C", $rem + $startChar));
		$bigInt = $quo;
	}
	join('', reverse(@chars));
}
